<?php

class Workset_Exception_Handler {

    protected static $_checkHttpCodes = array(401,402,403,404,500,501,502,503,504);

    protected static $_defaultErrorCode = 500;

    protected static $_redirect = null;

    protected static $_redirectCode = null;

    static function registerHandler($flag = true) {
        if (true == $flag) {
            set_exception_handler(array(
               __CLASS__,
               'handleException'
            ));
        }
    }

    static function setRedirect($url, $code = null) {
        self::$_redirect = (string)$url;

        if ($code > 100) {
            self::$_redirectCode = (int)$code;
        }
    }

    static function handleException(Exception $e) {
        $r = @include_once 'phplib.php';
        if (!$r) {
            return;
        }

        if (!class_exists('Zend_Loader_Autoloader') || null === Zend_Loader_Autoloader::getInstance()) {
            return;
        }

        $code = (int)$e->getCode();

        if (!in_array($code, self::$_checkHttpCodes)) {
            $code = self::$_defaultErrorCode;
        }

        if (!headers_sent()) {
            if (self::$_redirect !== null) {
                if (self::$_redirectCode) {
                    $code = self::$_redirectCode;
                }
                header('Location: '.self::$_redirect, true, $code);
                exit;
            }

            header('Content-Type:text/html;charset=UTF-8', true, $code);

        }
        
        if (APPLICATION_ENV == 'development') {
            $exception = new Zend_Exception($e->getMessage(), $code, $e);
            echo $exception->getMessage();
        } else {
            exit;
        }

    }

}

?>